package projet.volleystat;

import java.util.List;
import java.util.TreeMap;

import projet.volleystat.automate.VolleyStatistic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MarkPlayersAdapter extends ArrayAdapter<Player> {
	protected List<Player> players;
	protected VolleyStatistic stats;
	protected DBInfo dbinfo;

	public MarkPlayersAdapter(Context context, int ressource,
			List<Player> players) {
		super(context, ressource, players);
		this.players = players;
		dbinfo = new DBInfo(getContext());
		try {
			dbinfo.loadAll();
		} catch (DatabaseException e) {
			e.printStackTrace();
		}
		stats = new VolleyStatistic(dbinfo);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;

		if (v == null) {
			LayoutInflater vi = LayoutInflater.from(getContext());
			v = vi.inflate(R.layout.listitemlineplayerstat, null);
		}

		Player player = players.get(position);

		if (player != null) {
			TextView txtfirstname = (TextView) v
					.findViewById(R.id.stattextfirstname);
			TextView txtname = (TextView) v.findViewById(R.id.stattextname);
			TextView txtstat = (TextView) v.findViewById(R.id.stattextmark);

			if (txtfirstname != null)
				txtfirstname.setText(player.getFirstname());
			if (txtname != null)
				txtname.setText(player.getName());
			if (txtstat != null) {
				TreeMap<String, Double> statsplayer = new TreeMap<String, Double>();
				try {
					statsplayer = stats.analysisPlayer(player.getId());
				} catch (DatabaseException e) {
					e.printStackTrace();
				}
				Double points = statsplayer.get("point");
				Double faults = statsplayer.get("faute");
				Double mark;

				if (points == 0) {
					if (faults == 0) {
						txtstat.setText("N/A");
					} else {
						mark = -(faults * 10);
						txtstat.setText(Long.toString(Math.round(mark)) + " %");
					}
				} else {
					mark = ((points - faults) / points) * 100;
					txtstat.setText(Long.toString(Math.round(mark)) + " %");
				}
			}
		}

		return v;

	}

}
